package top.codedance.iotp.tools.serverTool.ui;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.iot.sdk.StandandService;
import top.codedance.iotp.iot.sdk.po.sync.BaseParam;
import top.codedance.iotp.tools.serverTool.ServerToolApplication;
import top.codedance.iotp.tools.terminal.TerminalApplication;
import top.codedance.iotp.tools.terminal.ui.WaitLoading;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.net.URL;

/**
 * @author Lenovo
 */
public class ViewOnlineDevicesFrame extends javax.swing.JDialog {
    private WaitLoading waitLoading = new WaitLoading(this);
    private MainFrame mf;
    private StandandService standandService;
    private BaseParam baseParam;
    private DefaultTableModel dtm;

    /**
     * Creates new form ViewOnlineDevicesFrame
     */
    public ViewOnlineDevicesFrame(MainFrame mf) {
        super(mf, true);
        this.mf = mf;
        initComponents();
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo.gif");
        ImageIcon icon = new ImageIcon(url);
        setIconImage(icon.getImage());
        setMinimumSize(new Dimension(1062, 643));
        setLocationRelativeTo(this.mf.getShellFrame());
        setTitle("代码飞舞采控系统-查看在线设备");
        this.standandService = new StandandService(ServerToolApplication.serverConf.getServerHost());
        baseParam = new BaseParam();
        baseParam.setUsername(ServerToolApplication.serverConf.getUsername());
        baseParam.setPassword(ServerToolApplication.serverConf.getPassword());

        initTable();
    }

    private void initTable() {
        String[] columnNames = {"deviceId"};
        Object[][] tdata = new Object[0][0];
        dtm = new DefaultTableModel(tdata, columnNames);
        device_jt.setModel(dtm);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        viewBn = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        device_jt = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        viewBn.setText("刷新");
        viewBn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewBnActionPerformed(evt);
            }
        });

        device_jt.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
                        {},
                        {},
                        {},
                        {}
                },
                new String[]{

                }
        ));
        device_jt.setToolTipText("");
        device_jt.setRowHeight(30);
        jScrollPane3.setViewportView(device_jt);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jScrollPane3)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(viewBn)
                                                .addGap(0, 521, Short.MAX_VALUE)))
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(viewBn, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void viewBnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewBnActionPerformed
        waitLoading.open();
        TerminalApplication.pool.submit(() -> {
            try {
                JSONObject jsonObject = standandService.getAllRegistedDeviceIds(baseParam);
                Integer status = jsonObject.getInteger("status");
                if (status == 200) {
                    initTable();
                    JSONArray data = jsonObject.getJSONArray("data");
                    String tmpJo;
                    for (int i = 0; i < data.size(); i++) {
                        tmpJo = data.getString(i);
                        dtm.addRow(new Object[]{tmpJo});
                    }
                } else {
                    JOptionPane.showMessageDialog(rootPane, "请求失败：" + jsonObject.getString("message"));
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(rootPane, "更新失败");
            } finally {
                waitLoading.close();
            }
        });
    }//GEN-LAST:event_viewBnActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable device_jt;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton viewBn;
    // End of variables declaration//GEN-END:variables
}
